//
//  SFStatusPictureView.swift
//  SFWeiBo
//
//  Created by 孙凡 on 16/4/13.
//  Copyright © 2016年 Edward. All rights reserved.
//SFStatusPictureView

import UIKit
import SnapKit
import SDWebImage

let ScreenW = UIScreen.mainScreen().bounds.size.width

//  图片间距
let PictMargin: CGFloat = 5

//cell的重用标示
let StatusCellId = "statusCellId"

class SFStatusPictureView: UICollectionView {

    var cellConstrain: Constraint?
//    var imageConstrain: Constraint?


    //设置每一张图片的宽高
    let pictWH: CGFloat = CGFloat(Int(ScreenW - 2 * PictMargin - 2 * SFStatusCellMargin)/3)

    var pic_urls: [SFThumbnail]?{

        didSet{


            //根据传进来图片张数来确定宽高

            self.cellConstrain?.uninstall()

            self.snp_makeConstraints { (make) in

                self.cellConstrain = make.size.equalTo(sizeFromPictureCount(pic_urls!)).constraint
            }

            reloadData()
        }



    }

    /**通过传入图片数量计算的宽高*/
    func sizeFromPictureCount(pic_urls: [SFThumbnail]) -> CGSize {

        let picCount = pic_urls.count

        if picCount == 1 {

            //拿到对应的图片名字
            let urlString = pic_urls.first?.thumbnail_pic

            //去缓存中找
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)

            if image != nil {

                var size: CGSize = image.size

                if size.width < 100 || size.height < 100{

                    size.width = 100
                    size.height = size.width / image.size.width * image.size.height



                } else if size.width > 200 || size.height > 200{

//                    size.width = 150
//                    size.height = size.width / image.size.width * image.size.height
                    size.height = 150
                    size.width = size.height / image.size.height * image.size.width
                }

//                var size: CGSize = image.size
//
//                if size.width < 100 {
//
//                    size.width = 100
//                    size.height = size.width / image.size.width * image.size.height
//
//                    if size.height > 200 {
//
//                        size.height = 200
//                        size.width = size.height / image.size.height * image.size.width
//                    }
//
//                } else if size.width > 200 {
//
//                    size.width = 200
//                    size.height = size.width / image.size.width * image.size.height
//
//                    if size.height > 200 {
//
//                        size.height = 200
//                        size.width = size.height / image.size.height * image.size.width
//                    }
//                }




//            if size.height > 150 {
//                size.height = 150
//                size.width = size.height / image.size.height * image.size.width
//            } else if size.height < 80 {
//                size.height = 80
//                size.width = size.height / image.size.height * image.size.width
//
//            }


            //设置item的大小
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = size

                return size
            }

        }

        //设置item的大小



        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout

        layout.itemSize = CGSizeMake(pictWH, pictWH)

//        imageView.snp_makeConstraints { (make) in
//
//            make.leading.top.bottom.trailing.equalTo(contentView).constraint
//        }


        //计算有多少列有多少行
        let row = (picCount - 1) / 3 + 1
        let col = picCount == 4 ? 2 : picCount > 3 ? 3 : picCount

        //计算宽度和高度
        let width: CGFloat = CGFloat(col) * pictWH + PictMargin * (CGFloat(col) - 1)

        let height: CGFloat = CGFloat(row) * pictWH + PictMargin * (CGFloat(row) - 1)

        return CGSizeMake(width, height)
    }


    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {

        super.init(frame: frame, collectionViewLayout: layout)

        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){

        backgroundColor = SFRandom()

        //注册cell
        registerClass(SFStatusPictCell.self, forCellWithReuseIdentifier: StatusCellId)

        //设置代理
        self.dataSource = self

        //设置layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout

        layout.itemSize = CGSizeMake(pictWH, pictWH)
        layout.minimumLineSpacing = PictMargin
        layout.minimumInteritemSpacing = PictMargin
    }

}

extension SFStatusPictureView: UICollectionViewDataSource{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic_urls?.count ?? 0

    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusCellId, forIndexPath: indexPath) as! SFStatusPictCell

        cell.contentView.backgroundColor = SFRandom()

        //取到每一张图片的url
        let thumbnail: String = pic_urls![indexPath.item].thumbnail_pic!

        cell.thumbnail = thumbnail

//        cell.thumbnail = pic_urls![indexPath.item]

        return cell
    }


}

class SFStatusPictCell: UICollectionViewCell {

    var thumbnail: String?{

        didSet{

            imageView.sd_setImageWithURL(NSURL(string: thumbnail!))

        }


    }

    override init(frame: CGRect) {
        super.init(frame: frame)


        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){


        self.contentView.addSubview(imageView)

        imageView.snp_makeConstraints { (make) in

            make.leading.top.bottom.trailing.equalTo(contentView).constraint
        }

    }


    lazy var imageView: UIImageView = {

        let imageView = UIImageView()

        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true

        return imageView
    }()

    
}


